import fmt
import sys, os
import struct
import inspect

AUTHOR = "affggh"
VERSION = 1.3

def main(infile, verbose=False):
    if os.path.isfile(infile):
        with open(infile, 'rb') as f:
            for name, class_ in inspect.getmembers(sys.modules['fmt'], inspect.isclass):
                if class_().mode == "bin":
                    if os.stat(infile).st_size < struct.calcsize(class_().structstr):
                        continue   # 如果文件比读取还小就跳过本次循环
                    if class_().offset == -1:
                        f.seek(0, 0)
                        if not class_().readinfo(f.read(class_().bufsize), verbose) == None:
                            print(class_().retfmt)
                    else:
                        f.seek(class_().offset, 0)
                        if not class_().readinfo(f.read(struct.calcsize(class_().structstr)), verbose) == None:
                            print(class_().retfmt)
                elif class_().mode == "ext":
                    if hasattr(class_, 'readinfo'):
                        class_().readinfo(infile, verbose)
                    if infile.endswith(class_().ext):
                        print(class_().retfmt)
                else:
                    sys.stderr.write("Error : Unknow detection mode!\n")
                    sys.exit(1)
    else:
        sys.stderr.write("Error : File does not exist!\n")
        sys.exit(1)

if __name__ == "__main__":
    import argparse
    parser = argparse.ArgumentParser(prog="gettype", 
                                     description="\tAUTHOR[%s]\tVERSION[%s]" %(AUTHOR, VERSION),
                                     epilog="This is a unstable tool, use it as your own risks")
    parser.add_argument('-i', '--input', help="[MUST]File input")
    parser.add_argument('-v', '--verbose', help="show more detials", type=bool, nargs='?', default=False, const=True)
    args = parser.parse_args()
    if args.input == None:
        sys.stderr.write("You need define a input file!\n")
        parser.print_help()
        sys.exit(1)

    if not os.path.isfile(args.input):
        sys.stderr.write("Error : File does not exist!\n")
        sys.exit(1)
    main(args.input, args.verbose)